package com.gxa.admin.service.impl;



import com.gxa.admin.mapper.AdminMapper;
import com.gxa.admin.service.AdminService;
import com.gxa.o2o.core.exception.BusinessException;

import com.gxa.o2o.core.pojo.Admin;
import com.gxa.o2o.core.service.impl.BaseServiceImpl;
import com.gxa.o2o.core.utils.JsonUtils;
import com.gxa.o2o.core.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service("adminService")
public class AdminServiceImpl extends BaseServiceImpl<Admin> implements AdminService {
    // @Autowired
    @Resource
    AdminMapper adminMapper;

    @Resource
    RedisTemplate redisTemplate;

    //设置token前缀
    public static final String LOGIN_TOKEN="momoxixi??$";

    /**
     * 在spring和springboot中可直接对request实现注入/装配
     */
    @Autowired
    private HttpServletRequest request;

    /**
     * 普通登录的方法
     * @param admin
     * @return
     */
    @Override
    public Admin login(Admin admin) throws BusinessException {
        Admin admin1 = adminMapper.selectOne(admin);
        if (admin1==null){
            throw new BusinessException("账号或密码不对");
        }
        if (admin1.getStatus() != 1) {
            throw new BusinessException("登录失败,账号为解冻,请联系总管理员,或发送邮件admin@eshop.com");
        }

        redisTemplate.delete(LOGIN_TOKEN + admin1.getToken());
        //生成token，存储登录信息(json),利用处理后的UUID
//        String token = UUID.randomUUID().toString().replace("-", "");
        String token = UUIDUtil.getUid();
        admin1.setToken(token);
        //用户的最后一次登录时间
        admin1.setLastLoginTime(new Date());

        //处理登录
        // 设置ip,设置token,更新mysql
        admin1.setIpAddress(request.getRemoteAddr());


        // 完成持久化
        int i = adminMapper.updateByPrimaryKey(admin1);
        //把对应号码的token值存入redis
        redisTemplate.opsForValue().set(admin1.getPhone(),token);

        // 处理token
//        key 经过了加密
        String key = LOGIN_TOKEN + token;
        String value = JsonUtils.objectToJson(admin1);
        redisTemplate.opsForValue().set(key, value, 30, TimeUnit.MINUTES);
//        redisTemplate.opsForValue().set(LOGIN_TOKEN+token,JsonUtils.objectToJson(user),30);

        // redis添加token信息和过期时间
//        redisTemplate.opsForValue().set(LOGIN+token, JsonUtils.objectToJson(user),60*60*2, TimeUnit.SECEND);

        return admin1;
    }

    /**
     * 管理员验证码一件登录的方法
     * @param phone
     * @param code
     * @return
     * @throws BusinessException
     */
    @Override
    public Map<String, String> login(String phone, String code) throws BusinessException {

        // 处理短信验证
        //1.获取redis服务器存储的验证码
        Object smsCode = redisTemplate.opsForValue().get(SmsServiceImpl.LOGIN_SMS + phone);

        //2.验证码失效的判断,如果为空则抛出异常
        if (StringUtils.isEmpty(smsCode)) {
            throw new BusinessException("验证码不存在或已过期");
        }

        //3.对验证码做校验, 如果不一致则抛出异常
        if (!code.equals(smsCode)) {
            throw new BusinessException("验证码验证不通过,请稍后再试");
        }

        //校验完成, 从mysql数据库中查找用户信息
        // 使用JPA完成查询: 通过手机号
        Admin admin=new Admin();
        admin.setPhone(phone);
//        Admin byPhoneAdmin = adminMapper.searchAllByPhoneAdmin(phone);
        Admin byPhoneAdmin = adminMapper.selectOne(admin);

        // 删除验证码
        //redisTemplate.delete(SmsServiceImpl.LOGIN_SMS+phone);

        //如果用户不存在, 则匿名注册,匿名格式: "用户:"+phone , 并指定用户状态
        if (byPhoneAdmin == null) {
            throw new BusinessException("该用户不是管理员,请稍后再试");
        }

        // userbyPhone对象非空表示用户对象存在, 判断status
        if (byPhoneAdmin.getStatus() != 1) {
            throw new BusinessException("登录失败,账号为解冻,请联系总管理员,或发送邮件admin@eshop.com");
        }

        redisTemplate.delete(LOGIN_TOKEN + byPhoneAdmin.getToken());
        //生成token，存储登录信息(json),利用处理后的UUID
//        String token = UUID.randomUUID().toString().replace("-", "");
        String token = UUIDUtil.getUid();
        byPhoneAdmin.setToken(token);
        //用户的最后一次登录时间
        byPhoneAdmin.setLastLoginTime(new Date());

        //处理登录
        // 设置ip,设置token,更新mysql
        byPhoneAdmin.setIpAddress(request.getRemoteAddr());


        // 完成持久化
        int i = adminMapper.updateByPrimaryKey(byPhoneAdmin);

        // 处理token
//        key 经过了加密
        String key = LOGIN_TOKEN + token;
        String value = JsonUtils.objectToJson(byPhoneAdmin);
        redisTemplate.opsForValue().set(key, value, 30, TimeUnit.MINUTES);
//        redisTemplate.opsForValue().set(LOGIN_TOKEN+token,JsonUtils.objectToJson(user),30);

        // redis添加token信息和过期时间
//        redisTemplate.opsForValue().set(LOGIN+token, JsonUtils.objectToJson(user),60*60*2, TimeUnit.SECEND);
        Map<String, String> resulet = new HashMap<>();
        resulet.put("token", token);

        return resulet;
    }

}
